"use server";

import fs from "fs/promises";
import path from "path";
const baseDir = process.cwd();
const basePath =
  baseDir + (process.env.NODE_ENV === "production" ? "\\" : "\\public");

interface FileTree {
  folder: string;
  files: string[];
  children: FileTree[];
}

export const readFileTree = async (dirPath: string): Promise<FileTree[]> => {
  let dir = dirPath.startsWith(basePath) ? dirPath : basePath + dirPath;

  const fileTree: FileTree[] = [
    {
      folder: path.basename(dir),
      files: [],
      children: [],
    },
  ];

  try {
    const files = await fs.readdir(dir);
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      const filePath = dir + "\\" + file;
      const stats = await fs.stat(filePath);
      if (stats.isDirectory()) {
        fileTree[0].children.push({
          folder: path.basename(filePath),
          files: [],
          children: await readFileTree(filePath),
        });
      } else {
        fileTree[0].files.push(path.basename(filePath));
      }
    }
  } catch (err) {
    console.error("错误", err);
  } finally {
    return fileTree;
  }
};
